package cn.accjiyun.translator.control;

import java.util.Map;

import cn.accjiyun.translator.jframe.CommandlineDisplay;
import cn.accjiyun.translator.main.Main;
import cn.accjiyun.translator.util.AnalyzingXml;
import cn.accjiyun.translator.util.SearchYouDaoAPI;
import cn.accjiyun.translator.model.TextRoom;

public class Control {

	private TextRoom textRoom = Main.textRoom;

	public Control(String originaString) {

		textRoom.setOriginaString(originaString);
		new SearchYouDaoAPI(textRoom.getOriginaString()).start();
		try {
			Thread.sleep(200);
			new AnalyzingXml(textRoom);
			new CommandlineDisplay(textRoom);
			postResultOnPane();
			textRoom.clear();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void postResultOnPane() {
		Main.frame.getTextPane().setText(getResultText().toString());
	}

	public StringBuilder getResultText() {

		StringBuilder resultText = new StringBuilder();
		if (!textRoom.getErrorCode().equals("0")) {
			return resultText.append(textRoom.backErrorMessages());
		}
		if (textRoom.getUsphonetic().length() != 0) {
			resultText.append("音标：\n");
			resultText.append("美:[" + textRoom.getUsphonetic() + "]");
			resultText.append("\t英:[" + textRoom.getUkphonetic() + "]\n\n");
		}
		if ((textRoom.getTranslation().length() != 0 
				&& !textRoom.getTranslation().equals(textRoom.getOriginaString()))) {
			resultText.append("翻译：");
				resultText.append("\n" + textRoom.getTranslation() + "\n");
		}
		if (textRoom.getBasicExplains().length() != 0 
				&& !textRoom.getBasicExplains().equals(textRoom.getTranslation())) {
			resultText.append("基本释义：");
			resultText.append("\n" + textRoom.getBasicExplains() + "\n");
		}
		if (!textRoom.getWebExplains().isEmpty()) {
			resultText.append("网络释义:");
			for (Map.Entry<String, StringBuilder> entry : textRoom.getWebExplains().entrySet()) {
				resultText.append("\n" + entry.getKey() + ":" + entry.getValue());
			}
		}
		if (resultText.length() == 0) {
			return resultText.append("无查询结果！");
		}
		return resultText;
	}

}
